package cn.lyf.myblog.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.lyf.myblog.mybatis.entity.User;
import cn.lyf.myblog.mybatis.mappers.UserMapper;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.session.Session;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usr = (UsernamePasswordToken) token;
        User user = userMapper.selectByName(usr.getUsername());
        if (user == null)
            return null;
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("username", user.getUsername());
        session.setAttribute("uid", user.getUid());
        return new SimpleAuthenticationInfo("", user.getPassword(), "");
    }

}
